package io.renren.modules.zjwl.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.utils.ExcelReadUtils;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.zjwl.entity.DeviceAgentEntity;
import io.renren.modules.zjwl.service.DeviceAgentService;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.zjwl.dao.SimCardDao;
import io.renren.modules.zjwl.entity.SimCardEntity;
import io.renren.modules.zjwl.service.SimCardService;
import org.springframework.web.multipart.MultipartFile;


@Service("simCardService")
public class SimCardServiceImpl extends ServiceImpl<SimCardDao, SimCardEntity> implements SimCardService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private DeviceAgentService deviceAgentService;

    @Override
    public boolean updateExpireDateBatch(SimCardEntity simCardEntity) {
        if (CollectionUtil.isNotEmpty(simCardEntity.getSimcardIds())) {
            UpdateWrapper<SimCardEntity> updateWrapper = new UpdateWrapper<>();

            updateWrapper.in("id", simCardEntity.getSimcardIds());
            updateWrapper.set("expire_date", simCardEntity.getExpireDate());
            return this.update(updateWrapper);
        }
        return true;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SimCardEntity> queryWrapper = new QueryWrapper<>();
//        if (params.containsKey("agentUserId") && NumberUtil.isNumber(params.get("agentUserId").toString())) {
//
//            queryWrapper.eq("agent_user_id",
//                    Integer.parseInt(params.get("agentUserId").toString()));
//        }
        if (params.containsKey("agentId") && NumberUtil.isNumber(params.get("agentId").toString())) {

            queryWrapper.eq("agent_id",
                    Integer.parseInt(params.get("agentId").toString()));
        }
        if (ShiroUtils.getUserEntity().getAgentId() > 0) {
            queryWrapper.eq("agent_id", ShiroUtils.getUserEntity().getAgentId());
        }
        if (params.containsKey("expire") && Boolean.parseBoolean(params.get("expire").toString())) {
            queryWrapper.le("expire_date", new Date());
        } else {
            if (params.containsKey("overdue")) {
                int day = Integer.parseInt(params.get("overdue").toString());
                if (day > 0) {
                    Date now = new Date();
                    if (day == 7) {
                        Date overdueDate = DateUtil.offsetDay(now, day);
                        queryWrapper.le("expire_date", overdueDate);
                        queryWrapper.ge("expire_date", now);
                    } else {
                        Date overdueDate = DateUtil.offsetDay(now, 7);
                        Date endDate = DateUtil.offsetDay(now, 15);
                        queryWrapper.le("expire_date", endDate);
                        queryWrapper.ge("expire_date", overdueDate);
                    }
                }
            }
        }

        if (params.containsKey("simCode") &&
                StringUtils.isNotEmpty(params.get("simCode").toString())) {
            queryWrapper.eq("sim_code", params.get("simCode"));
        }
        if (params.containsKey("simMobile") &&
                StringUtils.isNotEmpty(params.get("simMobile").toString())) {
            queryWrapper.eq("mobile", params.get("simMobile"));
        }
        if (params.containsKey("deviceId") && NumberUtil.isNumber(params.get("deviceId").toString())) {
            queryWrapper.eq("device_id", Integer.parseInt(params.get("deviceId").toString()));
        }
        IPage<SimCardEntity> page = this.page(
                new Query<SimCardEntity>().getPage(params),
                queryWrapper
        );
//        compareUserName(page);
        compareAgentName(page.getRecords());
        return new PageUtils(page);
    }


    public void compareAgentName(List<SimCardEntity> simCardEntityList) {
        List<Integer> agentIds = new ArrayList<>();
        agentIds.addAll(simCardEntityList.stream()
                .map(SimCardEntity::getAgentId).collect(Collectors.toSet()));
        QueryWrapper<DeviceAgentEntity> agentEntityQueryWrapper = new QueryWrapper<>();
        agentEntityQueryWrapper.in("id", agentIds);
        if (CollectionUtil.isEmpty(agentIds)) {
            return;
        }
        List<DeviceAgentEntity> agentList = deviceAgentService.list(agentEntityQueryWrapper);
        if (CollectionUtil.isNotEmpty(agentList)) {
            Map<Integer, String> agentNameMap = agentList.stream()
                    .collect(Collectors.toMap(DeviceAgentEntity::getId, DeviceAgentEntity::getName));
            simCardEntityList.forEach(simCardEntity -> {
                simCardEntity.setAgentName(
                        agentNameMap.getOrDefault(simCardEntity.getAgentId(), ""));
            });
        }
    }

    public void compareUserName(IPage<SimCardEntity> page) {
        List<Integer> agentUserIds = new ArrayList<>();
        agentUserIds.addAll(page.getRecords().stream()
                .map(SimCardEntity::getAgentUserId).collect(Collectors.toSet()));
        QueryWrapper<SysUserEntity> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("user_id", agentUserIds);
        List<SysUserEntity> sysUserEntities = sysUserService.list(userQueryWrapper);
        if (CollectionUtil.isNotEmpty(sysUserEntities)) {
            Map<Long, String> userNameMap = sysUserEntities.stream()
                    .collect(Collectors.toMap(SysUserEntity::getUserId, SysUserEntity::getUsername));
            page.getRecords().forEach(simCardEntity -> {
                simCardEntity.setAgentUsername(
                        userNameMap.getOrDefault(simCardEntity.getAgentUserId().longValue(), ""));
            });
        }
    }

    @Override
    public void outputSimCard(List<Integer> simcardIds) {

    }

    @Override
    public boolean importSimCard(MultipartFile file, Integer agentUserId) {
        List<SimCardEntity> simCardEntityList = new ArrayList<>();
        simCardEntityList.addAll(ExcelReadUtils.analysisSimCard(file));
        List<SimCardEntity> addList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(simCardEntityList)) {
            List<String> simCodeList = simCardEntityList.stream()
                    .map(SimCardEntity::getSimCode).collect(Collectors.toList());
            QueryWrapper<SimCardEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("sim_code", simCodeList);
            queryWrapper.eq("agent_id", agentUserId);
            List<SimCardEntity> simCardEntities = list(queryWrapper);
            Set<String> insertedSimCodeSet = simCardEntities.stream()
                    .map(SimCardEntity::getSimCode).collect(Collectors.toSet());
            simCardEntityList.forEach(simCardEntity -> {
                if (!insertedSimCodeSet.contains(simCardEntity.getSimCode())) {
                    simCardEntity.setAgentId(agentUserId);
                    addList.add(simCardEntity);
                }
            });
            saveBatch(addList, 100);
        }
        return true;
    }

    @Override
    public boolean bindDeviceIdBySimCode(String deviceId, String simCode) {
        QueryWrapper<SimCardEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("sim_code", simCode);
        List<SimCardEntity> simCardEntityList = list(queryWrapper);
        if (CollectionUtil.isNotEmpty(simCardEntityList)) {
            simCardEntityList.forEach(simCardEntity -> {
                simCardEntity.setDeviceId(deviceId);
                updateById(simCardEntity);
            });
        }
        return true;
    }

}